package com.martinwj.service.impl;

import com.martinwj.dao.collection.ICollectionDAO;
import com.martinwj.dao.video.IVideoDAO;
import com.martinwj.entity.Collection;
import com.martinwj.entity.Video;
import com.martinwj.service.CollectionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @ClassName: CollectionServiceImpl
 * @Description: TODO
 * @author: martin-wj
 * @createDate: 2021-04-04
 */
@Service
public class CollectionServiceImpl implements CollectionService {

    @Autowired
    private ICollectionDAO iCollectionDAO;
    @Autowired
    private IVideoDAO iVideoDAO;

    /**
     * 收藏或删除指定视频
     * @param collection
     */
    public void save(Collection collection) {
        // 判断该视频是否已收藏过了
        int count = iCollectionDAO.countByMediaIdAndUserId(collection.getMediaId(), collection.getUserId());
        if (count==0) {
            // 添加收藏
            iCollectionDAO.insert(collection);
        } else {
            // 删除收藏
            iCollectionDAO.delete(collection);
        }
    }

    /**
     * 获取用户的视频收藏列表
     * @param userId 用户id
     * @return
     */
    public List<Map<String, Object>> listCollection(String userId) {
        List<Map<String, Object>> list = iCollectionDAO.listCollection(userId);
        if (list!=null && !list.isEmpty()) {
            // 查询最新一集
            int len = list.size();
            for (int i=0; i<len; i++) {
                String mediaId = list.get(i).get("media_id").toString();
                Video video = iVideoDAO.selectByMediaIdLast(mediaId);
                list.get(i).put("video", video);
            }
        }
        return list;
    }

    /**
     * 判断当前视频是否已被用户收藏过了
     * @param mediaId 媒体主键
     * @param userId 用户id
     * @return
     */
    public int countByMediaIdAndUserId(String mediaId, String userId) {
        return iCollectionDAO.countByMediaIdAndUserId(mediaId, userId);
    }

    /**
     * 删除收藏的视频
     * @param collection
     */
    public void delete(Collection collection) {
        iCollectionDAO.delete(collection);
    }


}
